/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：WeixpayreturnServlet   
 * 类描述：   微信回调接口
 * 创建人：zhangl 
 * 创建时间：2017年2月9日 下午2:03:32   
 * 修改人：zhangl
 * 修改时间：2017年2月9日 下午2:03:32   
 * 修改备注：   微信回调接口
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import com.lst.model.MstOrder;
import com.lst.model.OrderDetail;
import com.lst.model.vo.MstOrderVo;
import com.lst.service.MstOrderService;
import com.lst.service.MstTransactionService;
import com.lst.service.OrderDetailService;

/**
 * @ClassName: WeixpayreturnServlet
 * @Description: 微信回调接口
 * @author zhangl
 * @date 2017年2月9日 下午2:03:32
 *
 */
public class WeixpayreturnServlet extends BaseServlet {

	private MstOrderService mstOrderService = ctx.getBean(MstOrderService.class);

	private OrderDetailService orderDetailService = ctx.getBean(OrderDetailService.class);

	private MstTransactionService mstTransactionService = ctx.getBean(MstTransactionService.class);

	/**
	 * @Fields serialVersionUID 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		try {

			// 获取微信回调POST过来反馈信息

			BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line = "";
			String result = "";
			while ((line = reader.readLine()) != null) {
				result += line;
			}
			reader.close();

			logger.info("reqPara result: " + result);

			if(StringUtils.isEmpty(result)){
				logger.error("xml信息为空 " + result);

				throw new Exception("xml信息为空 ");

			} else {
				Map<String, String> params = new HashMap<String, String>();

				Document document = DocumentHelper.parseText(result);  
				Element root = document.getRootElement();  
				@SuppressWarnings("unchecked")
				List<Element> children = root.elements();
				logger.info("==============element start==================");
				for(Element ele: children){
					if(!StringUtils.isEmpty(ele.getName())){
						params.put(ele.getName(), ele.getText());
					}

					logger.info("reqPara " + ele.getName() + ":" + ele.getText());
				}
				logger.info("==============element end==================");

				// 商户订单号
				String out_trade_no = params.get("out_trade_no");

				// 微信交易号
				String transaction_id = params.get("transaction_id");

				// 交易状态
				String result_code = params.get("result_code");

				if (result_code.equals("SUCCESS")) {

					//记录流水表
					String statusValue = mstTransactionService.insertByWeix(params);

					logger.info("transaction history statusValue: " + statusValue);

					if (out_trade_no.indexOf("_") > -1) {
						out_trade_no = out_trade_no.substring(0,out_trade_no.lastIndexOf('_'));
					}

					// 更新微信订单中的流水号
					MstOrderVo ordervo = mstOrderService.selectOrderByTradeNo(out_trade_no);
					Integer oid = ordervo.getId();
					MstOrder o = new MstOrder();
					o.setId(oid);
					o.setAlipaytradeno(transaction_id);

					mstOrderService.updateByPrimaryKeySelective(o);
					// 待付款状态
					if (ordervo.getOrderStatus() == 27) {
						OrderDetail od = new OrderDetail();
						od.setId(ordervo.getOdid());
						od.setOrderstatus(234);

						orderDetailService.updateByPrimaryKeySelective(od);

						logger.info("修改订单状态为待参与  orderdetailid=" + ordervo.getOdid());
					}
				}

				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();

				out.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			}

		} catch (Exception e) {

			logger.error("doPost error: ", e);
		}
	}
}
